package com.qf.service.impl;

import com.qf.mapper.UserMapper;
import com.qf.pojo.User;
import com.qf.service.UserService;
import com.qf.util.ResultMsg;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@Service
public class UserServiceImpl implements UserService {

    @Autowired  //按类型注入
    private UserMapper userMapper;

    @Override
    public ResultMsg login(HttpServletResponse response,String name, String pass, String nolog, HttpServletRequest request) {//request
        ResultMsg msg=new ResultMsg();
        User user=userMapper.selectOne(name,pass);
        if(user==null){
            //登录失败
            msg.setCode(201);
            //将登录失败的用户名作回显
            msg.setMsg("登录失败");
        }else{
            //成功
            //cookie记录
            //创建：new Cookie(String,String);
            //获得：Cookie[] cks=request.getCookies();
            if("nolog".equals(nolog)){
                Cookie cookie = new Cookie(name, pass);//root=666
                //设置时间
                cookie.setMaxAge(60*60*24*7);
                //存储cookie
                response.addCookie(cookie);

            }
            //msg.setCode(200);
            //向session里存储用户信息
           HttpSession session= request.getSession();
            session.setAttribute("sys_user",user);
            msg.setData(user);
        }
        return msg;
    }

    @Override
    public ResultMsg regist(User user) {
        ResultMsg resultMsg=new ResultMsg();

        User u = userMapper.selectByName(user.getUname());

        if(u==null) {
            int res = userMapper.insert(user);
            if (res == 1) {
                resultMsg.setCode(200);
            } else {
                resultMsg.setCode(201);
            }
        }else{
            resultMsg.setCode(202);
            resultMsg.setMsg("昵称不可用");
        }
        return resultMsg;
    }

    @Override
    public ResultMsg checkName(String name) {
        ResultMsg resultMsg=new ResultMsg();
        User user = userMapper.selectByName(name);
        if(user==null){
            resultMsg.setCode(200);
            return resultMsg;
        }
        resultMsg.setCode(201);
        resultMsg.setMsg("用户名已被占用");
        return resultMsg;
    }
}
